package com.sdkj.recruit.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.sdkj.recruit.model.ResultCode;
import com.sdkj.recruit.model.ResultData;
import com.sdkj.recruit.service.IQiNiuService;
import com.sdkj.recruit.service.IShareService;
import com.sdkj.recruit.util.FileUploadUtil;
import com.sdkj.recruit.util.FileUploadUtil.UploadFileItem;
import com.sdkj.recruit.util.PropertiesUtil;
import com.sdkj.recruit.util.RequestContext;
import com.sdkj.recruit.util.StringUtil;
import com.sdkj.recruit.vo.FeedBackVo;
import com.sdkj.recruit.vo.PlatformShareVo;
import com.sdkj.recruit.vo.PraiseVo;
import com.sdkj.recruit.vo.ShareCommentVo;
import com.sdkj.recruit.vo.ShareTimesVo;
import com.sdkj.recruit.vo.SimpleModelVo;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@Path("/share")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class ShareController {

	@Autowired
	private IShareService shareService;
	
	@Autowired
	private IQiNiuService qiNiu;
	private static final Logger logger =Logger.getLogger(ShareController.class);
	
	private static final PropertiesUtil propertiesUtil = new PropertiesUtil("config.properties");

	
	/**
	 * 分享服务
	 * 
	 * @param showTimes
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/saveShare")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> saveShare(final ShareTimesVo showTimesVo, @Context HttpServletRequest request) {
		
		try {
			return shareService.saveShare(showTimesVo);

		} catch (Exception e) {
			return ResultCode.error("发布分享失败", null);

		}
	}
	
	
	/**
	 * 修改帖子
	 * @param showTimesVo
	 * @param request
	 * @return
	 */
	@Path("/edit")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> edit(final ShareTimesVo showTimesVo, @Context HttpServletRequest request) {
		
		try {
			return shareService.edit(showTimesVo);

		} catch (Exception e) {
			return ResultCode.error("修改失败", null);

		}
	}
	
	
	@Path("/platformShare")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> platformShare(final PlatformShareVo platformShare, @Context HttpServletRequest request) {
		
		try {
			return shareService.platformShare(platformShare);

		} catch (Exception e) {
			return ResultCode.error("分享失败", null);

		}
	}
	
	@Path("/autoUpdate")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> autoUpdate(@Context HttpServletRequest request) {
		
		try {
			return shareService.autoUpdate();

		} catch (Exception e) {
			return ResultCode.error("获取版本更新失败", null);
		}
	}
	

	@Path("/saveFormShare")
	@POST
	public ResultData<Object> saveFormShare(@Context HttpServletRequest request) {
		
		try {
			ShareTimesVo svo =new ShareTimesVo();
			if(StringUtil.isEmptyString(request.getParameter("shareType"))){
				return ResultCode.error("分享类型不能为空", null);
			}
			int shareType =Integer.valueOf(request.getParameter("shareType"));
			svo.setShareType(shareType);
            svo.setContent(request.getParameter("content"));
            svo.setPublishType(2);
            svo.setUserId(RequestContext.getUserId());
            List<String> shareUrls =new ArrayList<>();
            List<String> compressShareUrl =new ArrayList<>();
			if(shareType==1 || shareType==2 || shareType==4){
				final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(request);
				
				if(uploadFiles.length==0){
					return ResultCode.error("上传文件不能为空", null);
				}
				if(shareType ==4){
					if(uploadFiles.length>1){
						return ResultCode.error("语音只能上传1个", null);
					}
				}
				
				if(shareType ==1){
					if(uploadFiles.length>2){
						return ResultCode.error("视频只能上传1个", null);
					}
				}
				if(shareType==2){
					if(uploadFiles.length>6){
						return ResultCode.error("图片最多支持6张", null);
					}
				}
				
	            for (int t = 0; t < uploadFiles.length; t++) {
	                File file = uploadFiles[t].getInternalFile();
	                // 调用七牛云，上传信息
	                String fileId =qiNiu.upload(file);
	                String compress ="";
	                // 压缩一份
	                if(shareType==2){
	                	
	                	String compressPicPath =propertiesUtil.getProperty("compressPicPath")+"/"+new Date().getTime()+".jpg";
	                	float compressQualit =Float.parseFloat(propertiesUtil.getProperty("compressQualit"));
	                	Thumbnails.of(file.getPath()).scale(1f).outputQuality(compressQualit).toFile(compressPicPath);
	                	compress =qiNiu.upload(new File(compressPicPath));
	                	compressShareUrl.add(compress);
	                }
	                if(shareType==1){
	                	String fileType =uploadFiles[t].getFileType();
	                	// 视频封面
	                	if("jpg".equals(fileType) || "png".equals(fileType)){
	                		svo.setVideoPic(fileId);
	                		continue;
	                	}
	                	// 视频文件
	                	if("mp4".equals(fileType) || "MP4".equals(fileType) || "3gp".equals(fileType)){
	                		shareUrls.add(fileId);
	                	}
	                }
	                else{
	                	shareUrls.add(fileId);
	                }
	               
	            }
	            svo.setShareUrl(shareUrls);
	            svo.setCompressShareUrl(compressShareUrl);
			}
			if(shareType==5){
				svo.setLinkUrl(request.getParameter("linkUrl"));
			}
			shareService.saveShare(svo);
			return ResultCode.success("发布分享成功", svo);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultCode.error("发布分享失败", null);
		}
	}
	
	public static void main(String[] args) {
	    try {
	    	
            //ImageUtil.convert("D:/img/12.png", "jpg", "d:/img/34.jpg");

	    	Thumbnails.of("d:/img/wf.jpg").scale(1f).outputQuality(0.1f).toFile("d:/img/78.jpg");
	    	/*File f =new File("d:/12.txt");
	    	if(!f.exists()){
	    		f.createNewFile();
	    	}*/
	        //fetchFrame("d:/12.mp4", "D:/new/test4.jpg");
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}

	
	
	/**
	 * 删除分享
	 * 
	 * @param shareId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/deleteShare/{shareId}")
	@POST
	public ResultData<Object> deleteShare(@PathParam("shareId") final String shareId,
			@Context final HttpServletRequest request) throws IOException, Exception {
		
		try {
			return shareService.deleteShare(shareId);

		} catch (Exception e) {

			return ResultCode.error("删除分享失败", null);

		}
	}
	
	
	@Path("/increaseReadCount/{shareId}")
	@POST
	public ResultData<Object> increaseReadCount(@PathParam("shareId") final String shareId,
			@Context final HttpServletRequest request) throws IOException, Exception {
		try {
			return shareService.increaseReadCount(shareId);

		} catch (Exception e) {
			return ResultCode.error("增加阅读量失败", null);
		}
	}

	/**
	 * 点赞
	 * 
	 * @param userId
	 * @param shareId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/praise")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> praise(final PraiseVo praiseVo, @Context final HttpServletRequest request)
			throws IOException, Exception {
		
		try {
			return shareService.praise(praiseVo.getUserId(), praiseVo.getShareId());

		} catch (Exception e) {
			return ResultCode.error("点赞失败", null);
		}
	}
	
	
	@Path("/increasePraiseCount/{shareId}")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> increasePraiseCount(@PathParam("shareId") final String shareId, @Context final HttpServletRequest request)
			throws IOException, Exception {
		try {
			return shareService.increasePraiseCount(shareId);

		} catch (Exception e) {
			return ResultCode.error("点赞失败", null);
		}
	}

	/**
	 * 评论
	 * 
	 * @param shareCommentVo
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/comment")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> comment(final ShareCommentVo shareCommentVo, @Context final HttpServletRequest request)
			throws IOException, Exception {
		try {
			return shareService.comment(shareCommentVo);

		} catch (Exception e) {
			return ResultCode.error("评论失败", null);
		}
	}
	
	@Path("/deleteComment")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> deleteComment(final ShareCommentVo shareCommentVo, @Context final HttpServletRequest request)
			throws IOException, Exception {
		try {
			return shareService.deleteComment(shareCommentVo);

		} catch (Exception e) {
			return ResultCode.error("删除评论失败", null);
		}
	}

	/**
	 * 分享详情
	 * 
	 * @param shareId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/shareDetail/{shareId}")
	@GET
	public ResultData<Object> querShareById(@PathParam("shareId") final String shareId,
			@Context final HttpServletRequest request) throws IOException, Exception {
		try {
			return shareService.querShareById(shareId);

		} catch (Exception e) {
			return ResultCode.error("获取分享详情失败", null);
		}
	}

	/**
	 * 屏蔽帖子
	 * @param shareId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/shield")
	@POST
	public ResultData<Object> shield(@FormParam("shareId") final String shareId,@FormParam("optType") final int optType,
			@Context final HttpServletRequest request) throws IOException, Exception {
		try {
			return shareService.shield(shareId,optType);

		} catch (Exception e) {
			return ResultCode.error("获取分享详情失败", null);
		}
	}
	
	
	
	/**
	 * 分享详情
	 * 分享类型0:全部 1：视频 2:图片 3：笑话 4：语音 5：链接
	 * @param pageNo
	 * @param pageSize
	 * @param keyWord
	 * @param  queryType 1:post 2:latest 3:community
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/shareList")
	@GET
	public ResultData<Object> shareList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("shareType") final int shareType,
			@QueryParam("keyWord") final String keyWord, @QueryParam("queryType") final int queryType,
			@Context final HttpServletRequest request) throws IOException, Exception {
		try {
			return shareService.shareList(pageNo, pageSize, keyWord, shareType, queryType);
		} catch (Exception e) {
			return ResultCode.error("获取分享列表失败", null);
		}
	}
	
	/**
	 * 获取用户分享页面
	 * 当用户传的userId 跟当前登录用户userId 一样，则查询自己分享+回复的帖子
	 * 如果不一样，则查找别人分享的帖子
	 * @param pageNo
	 * @param pageSize
	 * @param userId 用户ID
	 * @param queryType 1：自己分享 2：回复
	 * 					 
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/userShareList")
	@GET
	public ResultData<Object> userShareList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("userId") final String userId,
			@QueryParam("queryType") final int queryType, @Context final HttpServletRequest request)
			throws IOException, Exception {
		try {
			return shareService.userShareList(pageNo, pageSize, userId, queryType);
		} catch (Exception e) {
			return ResultCode.error("获取分享列表失败", null);
		}
	}
	
	@Path("/feedback")
	@POST
	public ResultData<Object> feedback(final FeedBackVo feedBackVo, @Context final HttpServletRequest request)
			throws IOException, Exception {
		try {
			return shareService.feedback(feedBackVo);
		} catch (Exception e) {
			return ResultCode.error("反馈失败", null);
		}
	}
	
	
	
	
	/**
	 * 后台管理使用，获取贴了列表
	 * @param pageNo
	 * @param pageSize
	 * @param keyWord
	 * @param req
	 * @return
	 */
	@Path("/queryShareList")
    @GET
	public SimpleModelVo queryShareList(
			@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize,
			@QueryParam("content") final String content,
			@QueryParam("shareType") final int shareType,
			@QueryParam("nickName") final String nickName,
			@QueryParam("shareStartDate") final String shareStartDate,
			@QueryParam("shareEndDate") final String shareEndDate,
			@Context HttpServletRequest req) {
        
    	SimpleModelVo vo = new SimpleModelVo();
    	List<ShareTimesVo> list =shareService.queryShareList(pageNo,pageSize,content,shareType,nickName,shareStartDate,shareEndDate);
        vo.setShareList(list);
        vo.setCount(shareService.queryAllUserCount(content,shareType,nickName,shareStartDate,shareEndDate));
    	return vo;
    }
	
	
	/**
	 * 获取token类型
	 * 1:上传token 2：下载token
	 * @param tokenType
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/getToken")
	@GET
	public ResultData<Object> getToken(@QueryParam("tokenType") final String tokenType,
			@Context final HttpServletRequest request) throws IOException, Exception {
		try {
			return qiNiu.uploadToken();
		} catch (Exception e) {
			return ResultCode.error("获取七牛token失败", null);
		}
		
	}
	
	/**
	 * 获取配置信息
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/getConfig")
	@GET
	public ResultData<Object> getConfig(
			@Context final HttpServletRequest request) throws IOException, Exception {
		try {
			return shareService.getConfig();
		} catch (Exception e) {
			return ResultCode.error("获取配置信息失败", null);
		}
	}
}
